/*!
\copyright  Copyright (c) 2025 Qualcomm Technologies International, Ltd.
            All Rights Reserved.
            Qualcomm Technologies International, Ltd. Confidential and Proprietary.
\file
\brief      Helper APIs for audio connections
*/

#include "kymera_connect_utils.h"
#include "kymera_data.h"
#include "kymera_config.h"
#include <audio_output.h>
#include <chain.h>

void Kymera_ConnectIfValid(Source source, Sink sink)
{
    if (source && sink)
    {
        PanicNull(StreamConnect(source, sink));
    }
}

void Kymera_DisconnectIfValid(Source source, Sink sink)
{
    if (source || sink)
    {
        StreamDisconnect(source, sink);
    }
}

void Kymera_ConnectOutputSourceList(Source *source_list, uint8 source_count, uint32 output_sample_rate)
{
    audio_output_params_t output_params;

    memset(&output_params, 0, sizeof(audio_output_params_t));
    output_params.sample_rate = output_sample_rate;
    output_params.transform = audio_output_tansform_connect;
    for (uint8_t i = 0; i < source_count; i++)
    {
        if(source_list[i] != NULL)
        {
            AudioOutputAddSource(source_list[i], i);
        }
    }
    /* Connect the sources to their appropriate hardware outputs. */
    PanicFalse(AudioOutputConnect(&output_params));

    AudioOutputGainApplyConfiguredLevels(audio_output_group_main, 0, NULL);
}

uint16 Kymera_MapMicsToChainInputs(uint16 *mic_ids, Sink *mic_sinks, uint16 num_mics, kymera_chain_handle_t chain)
{
    const chain_config_t *chain_cfg = ChainGetConfig(chain);
    uint16 mapped_mics = 0;

    for (uint8 i = 0; i < chain_cfg->number_of_inputs; i++)
    {
        chain_endpoint_role_t ep_role = chain_cfg->inputs[i].endpoint_role;
        uint16 mic_id = Microphones_GetMicrophoneByRole(ep_role);
        if (MICROPHONE_NONE != mic_id)
        {
            PanicFalse(mapped_mics < num_mics);
            mic_ids[mapped_mics] = mic_id;
            mic_sinks[mapped_mics] = ChainGetInput(chain, ep_role);
            mapped_mics++;
        }
    }
    return mapped_mics;
}
